//
//  HXNewFeatureViewController.swift
//  DemoSinaWeibo
//
//  Created by Mon on 15/12/3.
//  Copyright © 2015年 Mon. All rights reserved.
//

import UIKit

private let reuseIdentifier = "reuseIdentifier"

/// 新特性界面
class HXNewFeatureViewController: UICollectionViewController {
    
    // MARK: - 属性
    /// 流水布局属性
    private let flowLayout = UICollectionViewFlowLayout()
    
    /// 定义背景图片的个数
    private let bkgAcount = 4
    
    // 空实现构造函数,实现流水布局
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(collectionViewLayout: flowLayout)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册cell
        collectionView?.registerClass(HXNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        prepareNewFeatureCell()
    }
    
    // 准备cell
    func prepareNewFeatureCell() {
        /// 想要改变collectionViewCell的frame需要找到对应的item的frame来修改
        flowLayout.itemSize = UIScreen.mainScreen().bounds.size
        
        /// 设置滚动方向
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        /// 设置取消图片之间的间距
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        /// 设置分页效果(collectionView才有分页的功能)
        collectionView?.pagingEnabled = true
        /// 设置取消弹簧效果
        collectionView?.bounces = false
    }
    
    // MARK: - 实现collectionView的数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bkgAcount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HXNewFeatureCell
        
        cell.imageIndex = indexPath.row
        
        return cell
    }
    
    //collectionView的代理方法,在完成显示cell后(停下来)做的事情
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
//        print("indexPath:\(indexPath)")
        //拿到正在显示的cell
        let visibleIndexPath = collectionView.indexPathsForVisibleItems().last!
        //主动判断当前cell
        if visibleIndexPath.item == bkgAcount - 1 {
            // 按钮是cell的动画,所以要cell来调用
            // 根据index来显示当前cell
            let cell = collectionView.cellForItemAtIndexPath(visibleIndexPath) as! HXNewFeatureCell
            cell.startButtonAnimation()
        }
    }
    
}

/// 自定义cell
class HXNewFeatureCell: UICollectionViewCell {
    
    // MRK: - cell需要知道显示什么图片
    /// 显示第几张图片
    private var imageIndex: Int = 0 {
        didSet {
            // 需要根据下标来确定显示什么图片
            bkgImageView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
        }
    }
    
    //添加背景并且约束
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        prepareUI()
    }
    
    func startButtonAnimation() {
        
        //在开始动画的时候让按钮显示
        startButton.hidden = false
        
        //设置按钮缩放x/y都为0
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        //添加动画--> 附带弹簧效果
        UIView.animateWithDuration(1, delay: 0.25, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            //清空动画为原始状态-->x/y都为1
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                print("按钮动画完成")
        }
    }

    func prepareUI() {
        //添加到collectionView中去
        contentView.addSubview(bkgImageView)
        contentView.addSubview(startButton)
        
        //取消父类约束
        bkgImageView.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        //添加背景约束(使用VFL)
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg": bkgImageView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg": bkgImageView]))
        
        //添加按钮约束
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        
        /// 有文本的控件不需要约束自身的宽高(前提是需要自适应文字大小)
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0))
    }
    
    // MARK: - 懒加载
    /// 背景图
    private lazy var bkgImageView: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    /// cell上面的按钮
    private lazy var startButton: UIButton = {
       let sb = UIButton()
        //设置button文字
        sb.setTitle("开始体验", forState: UIControlState.Normal)
//        sb.backgroundColor = UIColor.orangeColor()
        sb.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        sb.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        //设置自适应
        sb.sizeToFit()
        
        // 为按钮添加点击事件
        sb.addTarget(self, action: "startButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return sb
    }()
    
    // MARK: - 按钮点击事件
    func startButtonClick() {
        print("新特性开始按钮点击了")
//        (UIApplication.sharedApplication().delegate as? AppDelegate)?.switchController(true)
        AppDelegate.switchRootController(true)
    }
}

